if (window.jdiyAdmin === undefined) {
    window.jdiyAdmin = {
        ctx: '',
        info: function (msg, fn) {
            if (msg === null || '' === msg) msg = '操作成功';
            layui.layer.msg(msg);
            if (fn && typeof fn == 'function') fn();
        },
        error: function (msg, fn) {
            if (msg === null || msg === '') msg = "现出错误但错误信息为空，考虑服务器端空指针异常。请检查服务端代码。";
            layui.layer.msg(msg, {icon: 5, shift: 6, skin: 'jdiy-err-red-text'});
            if (fn && typeof fn == 'function') fn();
        },
        confirm: function (msg, yes, no) {
            layui.layer.confirm(msg, function (index) {
                layui.layer.close(index);
                if (yes && typeof yes == 'function') yes();
            }, no);
        },

        load: function (jq, url, prm, fn) {
            if (!jq.length) return;
            if (!url) url = jq.data('url');
            if(!url)return;
            let loading = layui.layer.load(0);
            jq.load(url, prm, function (r, s, o) {
                layui.layer.close(loading);
                if (o.getResponseHeader('mgmtTimeout') === 'yes') {
                    document.location.reload();
                    return;
                }
                if (fn && typeof fn == 'function') fn.call(jq, r, s, o);
            });
        },
        ajax: function (options) {
            var loading = layui.layer.load(0), fnS = options.success, fnE = options.error;
            options.error = function (xhr, ajaxOptions, thrownError) {
                layui.layer.close(loading);
                if (typeof fnE == 'function') fnE.call(null, xhr, ajaxOptions, thrownError);
                else jdiyAdmin.ajaxError(xhr, ajaxOptions, thrownError);
            };
            options.success = function (d) {
                layui.layer.close(loading);
                if (typeof fnS == 'function') fnS.call(null, d);
            };
            $.ajax($.extend({
                type: 'post',
                dataType: 'json',
                cache: false
            }, options));
        },
        ajaxDone: function (ret) {
            if (ret.code === 403) {
                alert('会话超时～ todo');
            } else if (ret.code !== 200) {
                if (ret.msg) layui.layer.alert(ret.msg, {
                    icon: 5,
                    title: '操作失败,返回错误:'
                });
            } else {
                layui.layer.msg(ret.msg ? ret.msg : "恭喜，操作成功！");
            }
        },
        ajaxError: function (xhr, ajaxOptions, thrownError) {
            layui.layer.alert("<div>Http status: " + xhr.status + " " + xhr.statusText + "</div>"
                + "<div>ajaxOptions: " + ajaxOptions + "</div>"
                + "<div>thrownError: " + thrownError + "</div>"
                + "<div>" + xhr.responseText + "</div>", {
                icon: 2,
                title: '操作失败,返回错误:'
            });
        },
        getLocalArea: function (o) {
            if(o.hasClass('localRefresh')||o.hasClass('layadmin-tabsbody-item'))return o;
            let con = o.parents('.localRefresh');/*若需要局部刷新，div添加localRefresh样式和data-url属性即可:*/
            if (con.length === 0) con = o.parents('.layadmin-tabsbody-item');/*若没有内嵌tab,就获取admin的主tab*/
            return con.first();
        },
        reloadTab: function (url, prm) {
            var tabContent = $(".layadmin-tabsbody-item.layui-show");
            if (tabContent) {
                if (url) jdiyAdmin.load(tabContent, url, prm);
                else {
                    var shForm = tabContent.find('.shForm');
                    if (shForm.length) shForm.submit();
                    else jdiyAdmin.load(tabContent);
                }
            }
        },
        closeDialog: function () {
            var dialog = $('.layui-layer'), n = dialog.length, it;
            while (n-- >= 0) {
                if ((it = $(dialog[n])).find('.dialogContent').length) {
                    layui.layer.close(parseInt(it.attr('times')));
                    break;
                }
            }
        },
        ajaxSubmit: function (form, callback) {
            var $form = $(form),
                dialog = $(form).parents('div.dialogContent'),
                isDialog = dialog.length;
            if (form._ids && form._ids.value) jdiyAdmin._selectedTableRowIds = form._ids.value;/*批量更新表单，让列表中数据仍然处于钩选状态*/
            if (callback == null || typeof callback != 'function') callback = function (ret) {
                jdiyAdmin.ajaxDone(ret);
                if (ret.code === 200) {
                    let localArea;
                    if (isDialog) {
                        jdiyAdmin.closeDialog();
                        console.log(dialog.attr('opener'));
                        localArea = jdiyAdmin.getLocalArea($('#' + dialog.attr('opener')));
                    } else {
                        localArea = jdiyAdmin.getLocalArea($form);
                    }
                    jdiyAdmin.load(localArea, null, localArea.attr('searchData'));
                } else if (ret.code === 203) {
                    jdiyAdmin.error(ret.msg);
                    try {
                        let device = layui.device();
                        if (!device.android && !device.ios) {
                            setTimeout(function () {
                                form[ret.inputId].focus();
                            }, 7);
                        }
                        let othis = $(form[ret.inputId]);
                        if ('SELECT' === form[ret.inputId].tagName) {
                            othis = othis.siblings('.layui-form-select');
                        }
                        othis.addClass('layui-form-danger');
                    } catch (e) {
                    }
                } else {
                    jdiyAdmin.error(ret.msg);
                }
            };
            if ($form.attr('enctype') !== 'multipart/form-data') {
                jdiyAdmin.ajax({
                    type: form.method || 'POST',
                    url: $form.attr("action"),
                    data: $form.serializeArray(),
                    success: callback
                });
                return false;
            } else {
                var _if = $("#callbackframe");
                if (_if.length === 0) {
                    _if = $("<iframe id='callbackframe' name='callbackframe' src='about:blank' style='display:none'></iframe>").appendTo("body");
                }
                if (!form.ajax) {
                    $form.append('<input type="hidden" name="ajax" value="1" />');
                }
                form.target = "callbackframe";
                var loading = layer.load(0),
                    iframe = _if[0];
                _if.bind("load", function () {
                    layer.close(loading);
                    _if.unbind("load");
                    if (iframe.src === "javascript:'%3Chtml%3E%3C/html%3E';" || /*For Safari*/
                        iframe.src === "javascript:'<html></html>';") { /* For FF, IE*/
                        return;
                    }
                    var doc = iframe.contentDocument || iframe.document, ret;
                    if (doc.readyState && doc.readyState !== 'complete') return;
                    if (doc.body && doc.body.innerHTML === "false") return;
                    if (doc.XMLDocument) {
                        ret = doc.XMLDocument;
                    } else if (doc.body) {
                        try {
                            ret = _if.contents().find("body").text();
                            ret = jQuery.parseJSON(ret);
                        } catch (e) {
                            ret = doc.body.innerHTML;
                        }
                    } else {
                        ret = doc;
                    }
                    callback(ret);
                });
                return true;
            }
        },
        listDone: function (res, curr, count, tableFilter) {/*为了让批量更新表单提交后，列表中目标行仍处于钩选状态*/
            $('div[lay-id=' + tableFilter + '] .jdiy-list-imgField').viewer({url:'src'});//图片查看器

            if (!jdiyAdmin._selectedTableRowIds) return;
            let data = res.data, num = 0, i;
            for (i = 0; i < data.length; i++) {
                if ((',' + jdiyAdmin._selectedTableRowIds + ',').indexOf(',' + data[i]['_id_'] + ',') !== -1) {
                    num++;
                    let index = data[i]['LAY_TABLE_INDEX'];
                    data[i].LAY_CHECKED = true;
                    $('div[lay-id=' + tableFilter + '] tr[data-index=' + index + '] input[type="checkbox"]')
                        .prop('checked', true).next().addClass('layui-form-checked');
                }
            }
            let limit = parseInt($(".layui-laypage-limits").find("option:selected").val()); //分页数目
            if ((num === limit || num === count) && count > 0) {
                $('div[lay-id=' + tableFilter + '] .layui-table-header table.layui-table thead th input[type="checkbox"]')
                    .prop('checked', true)
                    .next().addClass('layui-form-checked');
            }
            delete jdiyAdmin._selectedTableRowIds;
            //layui.form.render();

        },
        deleteStore: function (o, id, field, key, dir, table) {
            jdiyAdmin.confirm("此操作将立即删除此文件，确定要这样做吗？", function () {
                jdiyAdmin.ajax({
                    url: jdiyAdmin.ctx + "/mgmt/JDiy/store.delete",
                    data: {id: id, field: field, key: key, dir: dir, table: table || ''},
                    success: function (ret) {
                        jdiyAdmin.ajaxDone(ret);
                        if (ret.code === 200) jdiyAdmin.load(jdiyAdmin.getLocalArea($(o)));
                    }
                });
            });
        },
        removeAttachUrl: function (o, id, table, field, url) {
            jdiyAdmin.confirm("此操作将立即移除此文件，确定要这样做吗？", function () {
                jdiyAdmin.ajax({
                    url: jdiyAdmin.ctx + "/mgmt/JDiy/noStore.delete",
                    data: {id: id, table: table, field: field, url: url},
                    success: function (ret) {
                        jdiyAdmin.ajaxDone(ret);
                        if (ret.code === 200) jdiyAdmin.load(jdiyAdmin.getLocalArea($(o)));
                    }
                });
            });
        },
        util: {
            nextInt: 0,/*JDiy20210901:用于为相应元素指定唯一ID等,用时后面都跟++ */
            newId: () => {
                let e = (a, t) => {
                    let j = a.length, x = Math.floor(t / j), y = t % j;
                    return x < j ? (x === 0 ? '' : a[x] + a[y]) : e(a, x) + a[y];
                };
                return 'j' + e("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(''), new Date().getTime() - 1622390400000);//-1622390400000:2021-05-31
            },
            url: function (url) {
                let __inst = function (url) {
                    let _loc = document.location;
                    if (url == null || url === "") url = _loc.href;
                    let anchor = "";
                    if (url.indexOf("#") !== -1) {
                        anchor = url.substring(url.indexOf("#"));
                        url = url.substring(0, url.indexOf("#"));
                    }
                    let file, prma, t_mh;
                    if (t_mh = url.match(/(.*?)\?(.*)/)) {
                        file = t_mh[1];
                        prma = t_mh[2];
                    } else if (t_mh = url.match(/(.+?=.*)+/)) {
                        file = "";
                        prma = url;
                    } else {
                        file = url;
                        prma = "";
                    }
                    let _names = ":" + prma.replace(/=[^&]*/g, "=:").replace(/&/g, "");
                    prma = prma === '' ? [] : prma.replace(/&amp;/i, '&').split("&");


                    this.set = function (name, value) {
                        if (typeof (name) == 'string' && name !== '') {
                            if (value != null) {
                                this.del(name);
                                prma.push(name + "=" + encodeURIComponent(value));
                            } else {
                                var sa = name.replace(/&amp;/i, "&").split("&");
                                if (sa.length) {
                                    for (let x = 0; x < sa.length; x++) {
                                        let kv = sa[x].split('=');
                                        if (kv.length === 2) {
                                            this.del(kv[0]);
                                            prma.push(sa[x]);
                                        }
                                    }
                                }
                            }
                        } else if (typeof (name) == 'object') {
                            for (var pty in name) {
                                if (name.hasOwnProperty(pty)) {
                                    var t = name[pty];
                                    if (typeof (t) == 'object' || typeof (t) == 'function') continue;
                                    this.set(pty, t);
                                }
                            }
                        }
                        return this;
                    };

                    this.getF = function () {
                        return file;
                    };

                    this.setF = function (f) {
                        file = (t_mh = f.match(/.*\?(.+)/)) ? t_mh[1] : f;
                        return this;
                    };

                    this.get = function (name) {
                        if (name) {
                            let sa = [], j = 0;
                            for (var i = 0, l = prma.length; i < l; i++) {
                                if (prma[i].indexOf(name + "=") === 0) sa[j++] = decodeURIComponent(prma[i].substring(name.length + 1));
                            }
                            if (sa.length)
                                return sa.length === 1 ? sa[0] : sa;
                            else
                                return null;
                        } else {
                            return prma.join("&");
                        }
                    };

                    this.del = function () {
                        let da = [], ds;
                        $.each(arguments, function () {
                            $.each(this.replace(/[;,]/, " ").split(/[\s;,]+/), function () {
                                da.push(this + "=");
                            });
                        });
                        ds = "|" + da.join("|");
                        for (let i = prma.length; i--;)
                            if (ds.indexOf("|" + prma[i].split("=")[0] + "=") !== -1) {
                                prma.splice(i, 1);
                            }
                        return this;
                    };

                    this.anchor = function (b) {
                        if (b) {
                            anchor = b.charAt(0) === '#' ? b : "#" + b;
                            return this;
                        } else {
                            return anchor === '' ? null : anchor.substring(1);
                        }
                    };

                    this.toString = function () {
                        url = file + (prma.length ? "?" + prma.join("&") : "");
                        return url + anchor;
                    };
                }
                return new __inst(url);
            }
        },
        got: {
            ajaxTodo: function (o, bodyID) {
                let confirm = $(o).attr('confirm'),
                    href = $(o).attr('href'),
                    fn = function (index) {
                        if (index !== undefined) layer.close(index);
                        jdiyAdmin.ajax({
                            url: href,
                            success: function (ret) {
                                jdiyAdmin.ajaxDone(ret);
                                if (ret.code === 200) {
                                    let localArea = jdiyAdmin.getLocalArea($('#' + bodyID));
                                    jdiyAdmin.load(localArea, null, localArea.attr('searchData'));
                                }
                            }
                        });
                    }
                if (confirm) layer.confirm(confirm, fn);
                else fn();
                return false;
            },
            dialog: function (o, bodyID) {
                let width = parseInt($(o).attr('width')) || 700,
                    height = parseInt($(o).attr('height')) || 450,
                    href = $(o).attr('href'),
                    btn = $(o).attr('btn'),//有这个属性表示不显示底部的确定和取消按钮
                    title = $(o).attr('title') || $(o).text();
                layer.open({
                    type: 8
                    , title: title
                    , content: href
                    , opener: jdiyAdmin.getLocalArea($('#' + bodyID)).attr('id')
                    , maxmin: true
                    , area: [width + 'px', height + 'px']
                    , btn: btn === 'false' ? [] : ['保存', '取消']
                    , yes: function (index, layero) {
                        //点击确认触发 iframe 内容中的按钮提交
                        layero.find("button[type=submit]").click();
                    }
                });
                return false;
            },
            tab: function (o, bodyID) {
                layui.index.openTabsPage($(o).attr('href'), $(o).attr('title') || $(o).text());
                if ($(o).parents('div.dialogContent').length) jdiyAdmin.closeDialog();
                return false;
            }
        }
    };
}